<style scoped>
.head-bg{width: 100%;}
.user-login{padding: 0 20px;padding-bottom: 20px;background: var(--color-bg-0);border-radius: 20px;margin-top: -20px;z-index: 2;position: relative;}
.user-login>h1{font-size: 36px;font-weight: bold;padding-top: 20px;}
.user-login .form-option{border-bottom: 1px solid #e7e7e7;width: 100%;padding: 20px 0 5px;}
.user-login .form-option input[type="text"],
.user-login .form-option input[type="password"]{background: none;border: none;outline: none;width: 100%;line-height: 40px;font-size: 20px;}

.user-login .submit{margin-top: 25px;}

.user-login .tips{font-size: 16px;margin-top: 25px;}
.user-login .tips .agree_row{margin: 0 5px;color: #007AFF;}
</style>
<template>
  <div class="page">
    <img-referrer class="head-bg" v-if="login_head_img" :src="login_head_img" />

    <form class="user-login" ref="form" @submit.prevent="onsubmit">
      <h1>{{ mode_map[mode] }}</h1>
      <div class="form-option flex">
        <input type="text" name="phone" v-model="param.phone" placeholder="请输入手机号" />
      </div>
      <div class="form-option flex" v-if="~['register','login_code'].indexOf(mode)">
        <input class="max" type="text" name="code" v-model="param.code" placeholder="请输入验证码" />
        <van-button size="small" round type="primary" @click="get_code">{{get_code_time>0?get_code_time+'秒后再次获取':'获取验证码'}}</van-button>
      </div>
      <div class="form-option flex" v-if="mode==='login_pass'">
        <input type="password" name="password" v-model="param.password" autocomplete="new-password" placeholder="请输入密码" />
      </div>
      <div class="form-option flex" v-if="mode==='register'">
        <input type="text" name="password" v-model="param.password" autocomplete="new-password" placeholder="请输入密码" />
      </div>
      <template v-if="mode==='register' || (!has_user&&mode==='login_code')">
        <input type="hidden" name="parent_phone" :value="param.parent_phone" v-if="share_phone_cache">
        <div class="form-option flex" v-else-if="required_parent_phone!==2">
          <input type="text" name="parent_phone" v-model="param.parent_phone" placeholder="请输入推荐电话" />
        </div>
      </template>

      <div class="tips flex" style="justify-content: space-between;">
        <span v-for="(v,k) in mode_map" v-show="mode!==k" @click="mode=k">{{ v }}</span>
      </div>

      <van-button class="submit" block round size="large" type="primary" native-type="submit">{{ mode==='register'?'注册':'登录' }}</van-button>

      <div class="tips flex" v-show="user_agreement.length" style="justify-content: center;">
        <van-checkbox v-model="agree">
          我已同意<span class="agree_row" v-for="row in user_agreement" @click="to_content(row.id)">{{ row.title }}</span>
        </van-checkbox>
      </div>
    </form>
    <img-code ref="img_code_obj" v-model:show="img_code.show" :img_data="img_code.img_data" @click:point="click_point" style="z-index: 5;"></img-code>
  </div>
</template>

<script>
import s94 from "s94-js";
import ImgCode from "@/components/ImgCode.vue";
import {_href, _url_api} from "@/js/s94_tool.js";
import form_param from "@/components/form_param.vue"
import {href_handle, _base, _get} from "@/vue_plugin/router_auto.js";
import {ajax, authorization} from "@/js/api_tool.js";
import {loading, msg} from "@/js/vant_tool.js";
import ImgReferrer from "@/components/widget/ImgReferrer.vue";
import {use_config_map} from "@/store/config_map.js";
import {use_this_user} from "@/store/this_user.js";



export default {
  components: {ImgReferrer, ImgCode, form_param},
  data: function(){
    let app = this;
    let _share_phone_ = s94.cache('_share_phone_');
    return {
      agree: false,
      required_parent_phone: parseInt(use_config_map().config.user?.new_user?.required_parent_phone || 0),
      share_phone_cache: _share_phone_,
      login_head_img: use_config_map().config.page?.img?.login_head_img,
      mode_map: {
        register: '立即注册',
        login_pass: '密码登录',
        login_code: '验证码登录',
      },
      has_user: true,
      mode: 'login_pass', // login_pass、login_code、register

      param: {
        phone: '',
        password: '',
        code: '',
        parent_phone: _share_phone_,
      },
      get_code_time: 0,

      img_code: {
        show: false,
        img_data(){
          return s94(function (resolve){
            ajax('/home/api/img_code', (res)=>{ resolve(res.data);return false; })
          })
        },
      },
      user_agreement: [],
    }
  },
  methods: {
    click_point(){},
    get_img_code(){
      let app = this;
      return new Promise((resolve)=>{
        this.$refs.img_code_obj.refresh();
        this.img_code.show = true;
        this.click_point = function (point_arr){
          resolve(point_arr[0]);
          app.img_code.show = false;
        }
      })
    },
    get_code_time_loop(){
      let time = s94.cache('last_send_phone_code_time', 0);
      let dt = Math.floor((time - Date.now())/1000)
      this.get_code_time = dt > 0 ? dt : 0;
      if (this.get_code_time > 0) setTimeout(()=>{this.get_code_time_loop()}, 1000);
    },
    get_code: function(){
      let app = this;
      if(this.get_code_time>0) return ;
      if (!this.agree) return msg.fail('请先同意条款');
      if(!/^1[0-9]{10}$/.test(this.param.phone)) return msg.fail('请填写正确的手机号码');
      let data = {
        phone: this.param.phone,
        // need_user: this.mode==='register' ? 0 : 1,
      };
      if (this.mode==='register') data.need_user = 0;
      this.get_img_code().then((point)=>{
        data = Object.assign(data, point);
        ajax({url:'/home/user/send_code', data:data, loading:1}, (res)=>{
          this.has_user = res.data==1;
          s94.cache({'last_send_phone_code_time': Date.now()+60000});
          this.get_code_time = 60;
          this.get_code_time_loop();
        }, (res)=>{
          if (s94.map(res, 'errors.left')) this.get_code();
        })
      })
    },
    onsubmit: function(){
      let app = this;
      if (!this.agree) return msg.fail('请先同意条款');
      if(!/^1[0-9]{10}$/.test(this.param.phone)) return msg.fail('请填写正确的手机号码');
      let data = {phone:this.param.phone};
      if (this.mode !== 'login_code'){
        if(!/^.+$/.test(this.param.password)) return msg.fail('密码必填');
        data.password = this.param.password;
      }
      if (this.mode !== 'login_pass'){
        if(!/^.+$/.test(this.param.code)) return msg.fail('验证码不能为空');
        data.code = this.param.code;
      }
      s94((resolve)=>{
        if (this.mode === 'login_pass') {
          this.get_img_code().then((point)=>{
            data = Object.assign(data, point);
            resolve(data);
          })
        }else {
          resolve(data);
        }
      }).then((data)=>{
        let url = this.mode === 'register' ? '/home/user/register' : '/home/user/login';
        let _wechat_user_ = s94.cache('_wechat_user_');
        if (_wechat_user_){
          data = Object.assign(data, _wechat_user_);
          data.head_img = data.headimgurl;
        }
        let _share_phone_ = s94.cache('_share_phone_');
        if (_share_phone_) data['parent_phone'] = _share_phone_;
        if (this.mode === 'register' || this.mode === 'login_code' ){
          data.parent_phone = s94.to_string(this.param.parent_phone);
        }
        ajax({url:url, data:data, method:'POST', loading:1}, (res)=>{
          use_this_user().$patch(res.data);
          this.login_after();
        })
      })
    },
    login_after(){
      let referer = s94.cache('user_login_referer', '/index');
      console.log(referer);
      href_handle(referer, 1500)
    },
    to_content(id){
      let href = `/model_base/info?model_name=content&id=${id}`;
      href_handle(href);
    },
    wechat_login(){
      loading.show('微信授权中...');
      let referer = s94.cache('user_login_referer', '') || _base()+'#/index';
      let url = _url_api('/home/api/wechat_oauth_login');
      let param = {
        referer: referer,
        authorization: authorization.get(url),
      }
      url += '?'+s94.param_encode(param)
      console.log(url, '微信授权地址');
      window.location.href = url;
    },
  },
  mounted() {
    this.get_code_time_loop();
    ajax("/home/user/user_agreement", ({data})=>{
      this.user_agreement = data;
      if (!data.length) this.agree = true;
    })
    if (use_this_user().id) return this.login_after();

    s94(()=>{
      if (_get('appid') && _get('openid')){
        this.mode = 'login_code';
      }else {
        this.wechat_login();
      }
    }, s94.OS_H5_WECHAT)
  }

}
</script>